package com.yzj.micro.demo.all.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yzj.demo.common.pojo.po.OrderPO;
import com.yzj.demo.common.pojo.po.StockPO;
import com.yzj.micro.demo.all.mapper.CartMapper;
import com.yzj.micro.demo.all.mapper.OrderMapper;
import com.yzj.micro.demo.all.mapper.StockMapper;
import com.yzj.micro.demo.all.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private StockMapper stockMapper;

    @Override
    public Boolean submitOrder(Integer userId, String productCode, Integer count) {
        //1.扣减库存 原库存1000个 count扣减掉
        //update stock_tbl set stock=stock-#{count} where product_code=#{productCode}
        UpdateWrapper<StockPO> updateWrapper=new UpdateWrapper<>();//和queryWrapper区别
        //可以封装set语句 queryWrapper只能封装where条件
        updateWrapper.setSql("stock=stock-"+count);
        updateWrapper.eq("product_code",productCode);
        //入参的第一个值 是一个StockPO对象,使用对象的非空属性拼接set
        int update = stockMapper.update(null, updateWrapper);
        //update>0 表示更新成功 找到了 数据 执行了更新
        //1.1 判断 扣减成功 继续
        //1.2 判断 扣减失败 return false
        if (update==0){
            //减库存失败的
            return false;
        }
        //2.生成订单 封装OrderPO 写入数据库
        OrderPO order=new OrderPO();
        order.setUserId(userId+"");
        order.setProductCode(productCode);
        order.setCount(count);
        //订单编号 保证唯一 使用uuid
        order.setOrderNo(UUID.randomUUID().toString());
        orderMapper.insert(order);
        //3.根据userId 和 productCode 删除购物车
        //delete from cart_tbl where user_id=#{userId} and product_code=#{productCode}
        QueryWrapper queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("product_code",productCode);
        cartMapper.delete(queryWrapper);
        return true;
    }
}
